<template>
  <div>
    <button @click="link">点击</button>
    <input v-model="msg" readonly />
  </div>
</template>

<script>

export default {
  name: "Test",
  data() {
    return {
      url:'',
      ws:null,
      msg:'',
    };
  },
  created() {
    this.url = "ws://127.0.0.1:8080/ws/socketLink"
  },
  mounted(){
    var that = this
    //连接打开时触发
    var ws = new WebSocket(this.url)
    that.ws = ws
    that.ws.onopen = function() {
      console.log("Connection open ...");
    };
    //接收到消息时触发
    that.ws.onmessage = function(evt) {
      console.log("Received Message: " + evt.data);
      that.msg = evt.data
    };
    //连接关闭时触发
    that.ws.onclose = function() {
      console.log("Connection closed.");
    };
  },
  methods: {
    link(){
      this.ws.send("Hello WebSockets!")
      //this.link()
    },
  },
};
</script>